import express from 'express';
import { query, param, validationResult } from 'express-validator';
import { Domain } from '../../models/index.js';
import { optionalAuth } from '../../middleware/auth.js';
import { catchAsync, BusinessError, NotFoundError } from '../../middleware/errorHandler.js';
import { success } from '../../utils/response.js';

const router = express.Router();

// 获取启用的领域列表（小程序公开接口）
router.get('/enabled',
  optionalAuth,
  catchAsync(async (req, res) => {
    const domains = await Domain.getEnabledDomains();

    res.json(success(domains, '获取启用领域列表成功'));
  })
);

// 获取领域详情（包含专家列表）
router.get('/:id',
  optionalAuth,
  [
    param('id').isInt({ min: 1 }).withMessage('领域ID必须是正整数')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { id } = req.params;
    
    const domain = await Domain.findByIdWithExperts(id);
    if (!domain) {
      throw new NotFoundError('领域不存在');
    }
    
    // 只返回启用的领域
    if (!domain.is_enabled) {
      throw new NotFoundError('领域不存在');
    }
    
    res.json(success(domain, '获取领域详情成功'));
  })
);

export default router;
